<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <link rel="StyleSheet" type="text/css" href="/tpa/admin.css" />
      <link rel="StyleSheet" type="text/css" href="/tpa/jquery-ui.css" />
      <link rel="StyleSheet" type="text/css" href="/tpa/jsTree.css" />
      <script type="text/javascript" src="/lib/js/jquery.js"></script>
      <script type="text/javascript" src="/lib/js/jquery.ui.js"></script>
      <script type="text/javascript" src="/lib/js/jquery.jstree.js"></script>
      {%assign var='fields_in_category' value=''%}
      {%if $c%}{%assign var='fields_in_category' value=$TR->meccano->in_category|cat:': '|cat:$categories[$c]->title%}{%/if%}
      <script type="text/javascript">
         var url = "/admin/interface{%if $c%}/{%$c%}{%/if%}.php";
         $(document).ready(function(){
            $('#tabedContent').tabs();
         });
      </script>
   </head>
   <body>
      <div id="tabedContent">
         <ul>
            <li><a href="#t_fields_a"><span>{%$TR->fields_tab->a%}</span></a></li>
            <li><a href="#t_fields_c"><span>{%$TR->fields_tab->c%}</span></a></li>
            <li><a href="#t_fields_u"><span>{%$TR->fields_tab->u%}</span></a></li>
            <li><a href="#t_fields_s"><span>{%$TR->fields_tab->s%}</span></a></li>
         </ul>

         {%foreach from=$data->tabs item='bfields' key='ft'%}
         <script type="text/javascript">
            {%strip%}
            var json_{%$ft%} = {attr:{id:"t0", rel: "root"}, data: "{%$TR->fields_tab->$ft%} {%$fields_in_category%}", state: "open", children: [
                  {%assign var='t' value='0'%}
                  {%foreach from=$bfields item='tab'%}
                  {%if $t neq 0%},{%else%}{%assign var='t' value='1'%}{%/if%}{
                     attr:{id:"t{%$tab->id%}",rel:"folder{%if $tab->active neq 1%}-del{%/if%}"},
                     data:{title:"{%$tab->title%}"},
                     state:"{%if $tab->fields|@count > 0 && $tab->active%}open{%else%}closed{%/if%}",
                     children:[
                        {%foreach from=$tab->fields item='field' name='f'%}
                        {
                           attr:{id:"f{%$field->id%}", rel:"field{%if $field->active neq 1%}-del{%/if%}"},
                           data:{title:"{%$field->title%} [{%$field->alias%}]"}
                        }
                        {%if !$smarty.foreach.f.last%},{%/if%}
                        {%/foreach%}
                     ]
                  }
                  {%/foreach%}
            ]};
            {%/strip%}
            
            $(document).ready(function(){
               jQuery("#t_fields_{%$ft%}").jstree({
                  "animation": 50,
                  'plugins': ['themes','json_data','contextmenu','dnd','types'],
                  'themes': {
                     'theme' : 'classic'
                  },
                  'json_data': {
                     'data': json_{%$ft%},
                     "ajax" : {
                        "url": url
                     }
                  },
                  types: {
                     "types": {
                        "root": {
                           icon: {image: "/tpa/img/tree/d.png", position: "-56px -90px"},
                           close_node: true
                        },
                        "folder-del": {
                           icon: {image: "/tpa/img/tree/d.png", position: "-57px -54px"}
                        },
                        "field": {
                           valid_children: "none",
                           icon: {image: "/tpa/img/tree/d.png", position: "-3px -73px"}
                        },
                        "field-del": {
                           valid_children: "none",
                           icon: {image: "/tpa/img/tree/d.png", position: "-3px -90px"}
                        }
                     }
                  },
                  contextmenu: {
                     items: function(n) {
                        var type = $(n).attr('id').substring(0,1);
                        var id = $(n).attr('id').substring(1);
                        var rel = $(n).attr('rel');
                        var cm = {};

                        if(id != 0)
                        {
                           cm.open = {
                              label: "{%$TR->meccano->edit|escape:'javascript'%}",
                              action: function(){
                                 parent.document.getElementById('content').src = '/admin/category/' + id + '.html';
                              },
                              icon: "/tpa/img/16/"+ (type == "n" ? "folder_edit.png" : "page_edit.png")
                           };
                           if(rel.indexOf('-del') !== -1)
                           {
                              cm.turnon = {
                                 label: "{%$TR->meccano->turnon|escape:'javascript'%}",
                                 action: function(n){
                                    $.get(url+'?a=1&id='+$(n).attr('id').substring(1), function(r){
                                       if(r)
                                       {
                                          updateNode(n, r)
                                       }
                                    },'json');
                                 },
                                 icon: "/tpa/img/16/power_on.png"
                              };
                           } else
                           {
                              cm.turnoff = {
                                 label: "{%$TR->meccano->turnoff|escape:'javascript'%}",
                                 action: function(n){
                                 $.get(url+'?a=2&id='+$(n).attr('id').substring(1), function(r){
                                       if(r)
                                       {
                                          updateNode(n, r);
                                       }
                                    },'json');
                                 },
                                 icon: "/tpa/img/16/power_off.png"
                              };
                           }
                        }
                        return cm;
                     }
                  }
               }).bind("move_node.jstree", function (e, data) {
                  $.ajax({
                     async: false,
                     type: 'POST',
                     url: url +'?a=3',
                     dataType: "json",
                     data: {
                        "node": $(data.rslt.o).attr("id"),
                        "parent": $(data.rslt.np).attr("id"),
                        "position": data.rslt.p,
                        "relate": $(data.rslt.r).attr("id")
                     },
                     success: function(r){
                        if(r == false)
                        {
                           $.jstree.rollback(data.rlbk);
                        }
                     },
                     error: function(){
                        $.jstree.rollback(data.rlbk);
                     }
                  });
               });
            });

            function updateNode(n, data)
            {
               console.log(data);
               var rel = $(n).attr('rel');
               params = {};
               if(data.active)
               {
                  params.rel = rel.replace('-del','');
               } else
               {
                  params.rel = rel+ '-del';
               }
               params.id = (data.tab ? 'f' : 't') + data.id;
               $(n).attr(params);
            }
         </script>
         <div id="t_fields_{%$ft%}"></div>
         {%/foreach%}

         <div id="t_fields_s">
            sorts
         </div>
      </div>
   </body>
</html>
{%*

<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <link rel="StyleSheet" type="text/css" href="/tpa/admin.css" />
      <link rel="StyleSheet" type="text/css" href="/tpa/jquery-ui.css" />
      <script type="text/javascript" src="/lib/js/jquery.js"></script>
      <script type="text/javascript" src="/lib/js/jquery.ui.js"></script>
      <script type="text/javascript" src="/lib/js/meccano.js"></script>
      <script type="text/javascript" src="/lib/js/field.editor.js"></script>
      {%assign var='fields_in_category' value=''%}
      {%if $c%}{%assign var='fields_in_category' value=$TR->meccano->in_category|cat:': '|cat:$categories[$c].title%}{%/if%}
      <script type="text/javascript">
         cMenu._MenuSets = {
            doc:[
               [editField,'{%$TR->meccano->open%}','doc_edit'],
               [hideField,'{%$TR->meccano->hide%}','hide']
            ]
         }

         $(document).ready(function(){
            $('#tabedContent').tabs();
            $('#cfields').meccanoTree({sortable:true,treeTitle:'{%$TR->fields_tab->c%} {%$fields_in_category%}',onDblClick:fieldEditor.edit,contextMenu:cMenu.buildContextMenu});
            $('#afields').meccanoTree({sortable:true,treeTitle:'{%$TR->fields_tab->a%} {%$fields_in_category%}',onDblClick:fieldEditor.edit,afterMove:checkFieldset,contextMenu:cMenu.buildContextMenu});
            $('#ufields').meccanoTree({sortable:true,treeTitle:'{%$TR->fields_tab->u%}'});
         });

         function editField(id)
         {
            var field = {};
            field.data = document.getElementById('field_'+id.replace(/a/, '')).params;
            fieldEditor.edit(field);
         }

         function hideField(id)
         {
            alert('under development');
         }

         function editField_old(e)
         {
            var id = e.data.id;
            if(typeof id == 'number')
            {
               $.ajax({
                  type:'GET',
                  url:'/admin/interface.php',
                  data:'a=3&id='+id,
                  dataType:'json',
                  success:function(data)
                  {
                     if(data != 0)
                     {
                        $('#f_id').val(data.id);
                        var html = '';
                        html += '<tr><td class="rt"><label for="f_title">{%$TR->meccano->fieldname%}:</label></td>';
                        html += '<td><input type="text" name="f[title]" id="f_title" value="'+ data.title +'" /></td></tr>';
                        if(data.params.type != 'image' && data.params.type != 'bind')
                        {
                           html += '<tr><td class="rt"><label for="f_value">{%$TR->meccano->defaultvalue%}:</label></td>';
                           html += '<td><input type="text" name="f[value]" id="f_value" value="'+ (typeof data.params.value != 'undefined'  ? data.params.value : '') +'" /></td></tr>';
                        }
                        if(data.params.type == 'string')
                        {
                           html += '<tr><td class="rt"><label for="f_html">{%$TR->meccano->multilinefield%}:</label></td>';
                           html += '<td><input type="checkbox" name="f[html]" id="f_html" value="1" ';
                           if(data.params.html) html += ' checked="checked"';
                           html += '/></td></tr>';
                           html += '<tr><td class="rt"><label for="f_height">{%$TR->meccano->height%}:</label></td>';
                           html += '<td><input type="text" name="f[height]" id="f_height" value="'+ (typeof data.params.height != 'undefined' ? data.params.height : 100) +'" /></td></tr>';
                           var emode = typeof data.params.emode != 'undefined' ? data.params.emode : 'Textarea';
                           html += '<tr><td class="rt"><label for="f_emode">{%$TR->meccano->editor_mode%}:</label></td>';
                           html += '<td><select name="f[emode]" id="f_emode">';
                           html += '<option value="Textarea"' + (emode == 'Textarea' ? ' selected' : '') + '>Textarea</option>';
                           html += '<option value="Plane"' + (emode == 'Plane' ? ' selected' : '') + '>Plane</option>';
                           html += '<option value="Basic"' + (emode == 'Basic' ? ' selected' : '') + '>Basic</option>';
                           html += '<option value="Simple"' + (emode == 'Simple' ? ' selected' : '') + '>Simple</option>';
                           html += '<option value="Advanced"' + (emode == 'Advanced' ? ' selected' : '') + '>Advanced</option>';
                           html += '</select></td></tr>';
                        } else if(data.params.type == 'select' || data.params.type == 'multiselect')
                        {
                           html += '<tr><td class="rt"><label for="f_values">{%$TR->meccano->langvar%}:</label></td>';
                           html += '<td><input type="text" name="f[values]" id="f_values" value="'+ (typeof data.params.values != 'undefined' ? data.params.values : '') +'" /></td></tr>';
                        } else if(data.params.type == 'image')
                        {
                           html += '<tr><td class="rt"><label for="f_min_w">{%$TR->meccano->minWidth%}:</label></td>';
                           html += '<td><input type="text" name="f[min_w]" id="f_min_w" value="'+ data.params.min_w +'" /></td></tr>';
                           html += '<tr><td class="rt"><label for="f_min_h">{%$TR->meccano->minHeight%}:</label></td>';
                           html += '<td><input type="text" name="f[min_h]" id="f_min_h" value="'+ data.params.min_h +'" /></td></tr>';
                           html += '<tr><td class="rt"><label for="f_max_w">{%$TR->meccano->maxWidth%}:</label></td>';
                           html += '<td><input type="text" name="f[max_w]" id="f_max_w" value="'+ data.params.max_w +'" /></td></tr>';
                           html += '<tr><td class="rt"><label for="f_max_h">{%$TR->meccano->maxHeight%}:</label></td>';
                           html += '<td><input type="text" name="f[max_h]" id="f_max_h" value="'+ data.params.max_h +'" /></td></tr>';
                           html += '<tr><td class="rt"><label for="f_ratio">{%$TR->meccano->imgRatio%}:</label></td>';
                           html += '<td><input type="checkbox" name="f[ratio]" id="f_ratio" value="1"' + (data.params.fixed ? ' checked="checked"' : '') + ' /></td></tr>';
                        } else if(data.params.type == 'bind')
                        {
                        	html += '<tr><td class="rt"><label for="f_min_w">{%$TR->meccano->allow_bind_article%}:</label></td>';
                        	html += '<td><input type="checkbox" name="f[articles]" id="f_articles" value="1"'+(data.params.articles ? ' checked="checked"': '')+' /></td></tr>';
                        	html += '<tr><td class="rt"><label for="f_min_w">{%$TR->meccano->allow_bind_category%}:</label></td>';
                        	html += '<td><input type="checkbox" name="f[categories]" id="f_categories" value="1"'+(data.params.categories ? ' checked="checked"': '')+' /></td></tr>';
                        }
                        html += '<tr><td></td><td><input type="button" name="commit" value=" {%$TR->meccano->save%} " onclick="saveField();" /></td></tr>';
                        $('#field_editor table').html(html);
                        $('#field_editor').show();
                     }
                  }
               });
            }
         }


         function saveField()
         {
            $.ajax({
               type:'GET',
               url:'/admin/interface.php',
               data:$('#field_editor form').serialize(),
               dataType:'json',
               success:function(data){
                  var field = document.getElementById('field_'+data.oid);
                  field.params.id = data.id*1;
                  $('#field_'+data.oid+' font').text(data.title);
                  $('#field_'+data.oid).attr('id', 'field_'+data.id);
               }
            });
            $('#field_editor').hide();
         }


         function AddNewField(belong)
         {
            alert(belong);
         }


         function reorderFields(list)
         {
            $('#' + list + '>li>ul').each(function(){
               var tabIndex = $(this).parent().attr('id').match(/\d+/g);
               $(':input[rel=tab]', this).each(function(){
                  $(this).val(tabIndex);
               });
            });
            position = 1;
            $('#' + list + ' :input[rel=position]').each(function(){
               $(this).val(position);
               position++;
            });
         }

         function checkFieldset(node)
         {
            // TODO: при перемещении обычного поля в сет - выводить его наружу
            // If field isn't in fieldset - exit
            if(typeof node[0].params.fieldset == 'undefined')
            {
               if(typeof node.parent().parent()[0].params.fieldset != 'undefined')
               {
                  $('li.fieldset_'+node.parent().parent()[0].params.fieldset, node.parent().parent().parent().parent()).before(node);
               }
               return false;
            }

            var fset = node[0].params.fieldset;
            // If moving fieldset - exit
            if(node.hasClass('fieldset_'+fset)) return true;

            // If field moved into own fieldset - exit
            if($(node).parent().parent().is('.fieldset_'+fset)) return true;

            var tmp    = node;
            var tab_f_id = false;
            // Get parent tab ID
            while((tab_f_id = tmp.parent().attr('id')) == '')
            {
                  tmp = tmp.parent();
            }
            // Find first own filedsets in tree Tab ID
            var tab_s_id = $('.fieldset_'+fset+':first', tmp.parent().parent()).parent().parent().attr('id');

            var tab_f_n = tab_f_id.match(/\d+/g);
            var tab_s_n = tab_s_id.match(/\d+/g);

            if((tab_f_n != 99 && tab_s_n == 99) || (tab_f_n == 99 && $('#'+tab_f_id+' .fieldset_'+fset).size() == 0))
            {
               // tree root ID: tmp.parent().parent().attr('id')
               var node_set = {
                  id:rand(10000,50000),
                  title:$('.fieldset_'+fset+' span:first').text(),
                  alias:fset,
                  folder:1,
                  active:1,
                  startup:0,
                  parent:tab_f_id,
                  fieldset:fset,
                  css:'fieldset_node'
               };
               $('#'+tmp.parent().parent().attr('id')).meccanoTree('addNode', node_set);
               $('#n'+node_set.id).addClass('fieldset_'+fset);
               if(tab_f_n != 99)
               {
                  tab_s_n = tab_f_n;
                  tab_s_id = tab_f_id;
               }
            }

            if(tab_f_n != 99)
            {
               $('#'+tab_s_id+' .fieldset_'+fset+':first li.last').before(node);
            } else if(tab_f_n == 99)
            {
               $('#'+tab_f_id+' .fieldset_'+fset+':first li.last').before(node);
            }

            // Delete empty fieldsets && Move fieldsets down of tab fields
            $('.fieldset_'+fset).each(function(){
               if($('>ul>li', this).size() < 2)
               {
                  $(this).remove();
               } else
               {
                  $('~ li.last', this).before(this);
               }
            });
         }
      </script>
      <style type="text/css">
         div.tree-root {background: url(/tpa/img/tree/fields.png) no-repeat 5px 0;}
      </style>
   </head>
   <body>
      <div id="tabedContent">
         <ul>
            <li><a href="#t_fields_a"><span>{%$TR->fields_tab->a%}</span></a></li>
            <li><a href="#t_fields_c"><span>{%$TR->fields_tab->c%}</span></a></li>
            <li><a href="#t_fields_u"><span>{%$TR->fields_tab->u%}</span></a></li>
            <li><a href="#t_fields_s"><span>{%$TR->fields_tab->s%}</span></a></li>
         </ul>


         {%foreach from=$data->tabs item='type_value' key='ft'%}
         <div id="t_fields_{%$ft%}">
            <form method="POST" action="/admin/interface{%if $c%}/{%$c%}{%/if%}.html">
               <input type="hidden" name="f[type]" value="{%$ft%}" />

               <ul id="{%$ft%}fields">
                  {%foreach from=$type_value key='tab_index' item='tab'%}
                  <li rel="{folder:1,active:{%$tab.active%},startup:0}"{%if $tab.fields|@count > 0 && $tab.active == 1%} class="open"{%/if%} id="tab_{%$ft%}_{%$tab_index%}">
                     <span>{%$tab.title%}</span>
                     {%if !empty($tab.fields)%}
                     <ul>
                        {%foreach from=$tab.fields item='field'%}
                        <li rel="{folder:0,active:{%$field->active%},startup:0,id:{%$field->id%},fieldset:'{%if !empty($field->fieldset)%}1{%else%}0{%/if%}'}" id="field_{%$field->id%}">
                                 <span>
                                    <input type="hidden" name="f[{%$field->id%}][position]" rel="position" value="{%$field->position%}" />
                                    <input type="hidden" name="f[{%$field->id%}][tab]" rel="tab" value="{%$field->tab%}" />
                                    <font>{%$field->title%}</font> [ {%$field->alias%} ]
                                 </span>
                              </li>
                        {%/foreach%}
                     </ul>
                     {%/if%}
                  </li>
                  {%/foreach%}
               </ul>
            </form>
         </div>
         {%/foreach%}
         
         <div id="t_fields_s"></div>

      </div>

      <div id="field_editor" style="border:1px solid #AAA;width:470px;position:absolute;top:50px;left:400px;display:none;">
         <div id="ThTitle"><div id="ThCloseLink"><a href="" onclick="$('#field_editor').hide(); return false;"><img src="/tpa/img/16/close.gif" width="16" height="16" /></a></div></div>
         <form action="/admin/interface.html">
            {%if $c%}<input type="hidden" name="c" value="{%$c%}" />{%/if%}
            <input type="hidden" name="a" value="4" />
            <input type="hidden" name="id" id="f_id" />
            <table border="0" cellpadding="0" cellspacing="0" style="margin:5px;">
            </table>
         </form>
      </div>
   </body>
</html>

*%}